package Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.Part;

public class UploadFileUtil {
	private Part part; // 包含文件的part
	private String path; // 文件存放的位置

	public Part getPart() {
		return part;
	}

	public void setPart(Part part) { // 设置part
		this.part = part;
	}

	public String getPath() { // 设置文件存放的位置（文件夹）
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}
	
	
	public String getFilename() { // 获取文件名
		String contentDispositionHeader = part.getHeader("content-disposition");
		System.out.println("contentDispositionHeader:::" + contentDispositionHeader);
		String[] elements = contentDispositionHeader.split(";");
		for (String element : elements) {
			if (element.trim().startsWith("filename")) {
				System.out.println(element);
				String filename = element.substring(element.indexOf('=') + 1).trim().replace("\"", "");
				int n = filename.lastIndexOf('\\');
				filename = filename.substring(n + 1);
				return filename;
			}
		}
		return null;
	}

	public int saveFile(String filename) {
		try {
			InputStream is = part.getInputStream();
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}

			FileOutputStream fos = new FileOutputStream(new File(dir, filename));
			byte[] buf = new byte[1024];
			int bytesRead;
			while ((bytesRead = is.read(buf)) != -1) {
				fos.write(buf, 0, bytesRead);
			}
			fos.flush();
			fos.close();
			is.close();
			return 1;
		} catch (IOException e) {
			e.printStackTrace();
			return 0;
		}
	}
}
